<template>
  <div class="rankRoot">
    <div class="rank">
      <div class="official">
        <h3 class="title">官方榜</h3>
        <list-table :tableData='v' v-for="v in  officialList" :key="v.id" @handleRowClick='handleRowClick' @handleDbClick='handleDbClick' @handleMoreClick='handleMoreClick'>
        </list-table>
      </div>
      <h3 class="title">全球榜</h3>
      <list-card :listCardData='globalList' @itemCardClick='handleMoreClick'></list-card>
    </div>
  </div>
</template>

<script>
let officialDom = null
import ListCard from '@/components/listCard/ListCard.vue'
import ListTable from '@/components/listTable/ListTable.vue'
import { reqTopList, reqMicDesc } from '@/network/api'
import { reactive, toRefs, onMounted, inject } from 'vue'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
export default {
  name: 'ranking',
  components: { ListCard, ListTable },
  setup() {
    const data = reactive({
      officialList: [],
      globalList: []
    })
    const store = useStore()
    const state = store.state
    const router = useRouter()
    const msg = inject('$message')

    const getTopList = async () => {
      const res = await reqTopList()
      const songs = res.list.slice(0, 4)
      data.globalList = res.list.slice(4)
      songs.forEach(v => {
        getMicDesc(v.id)
      })
    }
    const getMicDesc = async id => {
      const { code, playlist } = await reqMicDesc(id)
      if (code === 200) {
        playlist.tracks = playlist.tracks.slice(0, 5)
        data.officialList.push(playlist)
      }
    }

    const handleRowClick = e => {
      if (officialDom == null) {
        officialDom = document.querySelector('.official')
      }
      const dom = officialDom.querySelector('.selectRow')
      if (dom) {
        dom.classList.remove('selectRow')
      }
      e.classList.add('selectRow')
    }
    const handleDbClick = ({ id, index }) => {
      let micI = data.officialList.find(v => v.id === id)
      store.commit('updateMusicId', id)
      const musicList = data.officialList[micI]
      if (state.musicListId !== musicList.id) {
        store.commit('updateMusicList', {
          musicListId: musicList.id,
          musicList: musicList.tracks
        })
      }
    }
    const handleMoreClick = id => {
      if (state.isLogin === false) {
        msg.error('登陆后才能查看更多歌曲')
        return
      }
      router.push('/musiclistdetail/' + id)
    }
    onMounted(() => {
      getTopList()
    })
    return {
      ...toRefs(data),

      handleRowClick,
      handleMoreClick,
      handleDbClick
    }
  }
}
</script>

<style scoped>
.rankRoot {
  display: flex;
  justify-content: center;
  width: 100%;
}
.rank {
  max-width: 1000px;
  width: 100%;
}
.title {
  margin: 10px 0;
}
</style>